package com.atguigu.one.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.one.bean.UserRegisterBean;
import com.atguigu.one.utils.DateFormatUtil;
import com.atguigu.one.utils.MyClickHouseUtil;
import com.atguigu.one.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsUserUserRegisterWindow {
    public static void main(String[] args) throws Exception {
        //TODO 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //设置状态后端
        //        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
        //        env.getCheckpointConfig().setCheckpointTimeout(60*1000L);
        //        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
        //        env.getCheckpointConfig().enableExternalizedCheckpoints(
        //                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
        //        );
        //        env.setRestartStrategy(
        //                RestartStrategies.failureRateRestart(10, Time.of(1L, TimeUnit.DAYS),Time.of(3L,TimeUnit.DAYS))
        //        );
        //        env.setStateBackend(new HashMapStateBackend());
        //        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        //        System.setProperty("HADOOP_USER_NAME","atguigu");

        //TODO 2.读取Kafka中用户注册主题数据创建流 & 转换数据结构为JavaBean
        String topic = "dwd_user_register";
        String groupId = "user_register";
        SingleOutputStreamOperator<UserRegisterBean> userRegisterDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic,
                groupId))
                .map(new MapFunction<String, UserRegisterBean>() {
                    @Override
                    public UserRegisterBean map(String value) throws Exception {
                        JSONObject jsonObject = JSON.parseObject(value);

                        return new UserRegisterBean(
                                "", "",
                                1L,
                                DateFormatUtil.toTs(jsonObject.getString("create_time"), true)
                        );
                    }
                });

        //TODO 3.提取时间戳生成WaterMark
        SingleOutputStreamOperator<UserRegisterBean> userRegisterWithWmDS =
                userRegisterDS.assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserRegisterBean>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserRegisterBean>() {
                                    @Override
                                    public long extractTimestamp(UserRegisterBean element, long recordTimestamp) {
                                        return element.getTs();
                                    }
                                })
                );

        //TODO 4.开窗,聚合
        SingleOutputStreamOperator<UserRegisterBean> resultDS =
                userRegisterWithWmDS.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                        .reduce(new ReduceFunction<UserRegisterBean>() {
                                    @Override
                                    public UserRegisterBean reduce(UserRegisterBean value1, UserRegisterBean value2) throws Exception {
                                        value1.setRegisterCt(value1.getRegisterCt() + value2.getRegisterCt());
                                        return value1;
                                    }
                                },
                                new AllWindowFunction<UserRegisterBean, UserRegisterBean, TimeWindow>() {
                                    @Override
                                    public void apply(TimeWindow window, Iterable<UserRegisterBean> values,
                                                      Collector<UserRegisterBean> out) throws Exception {
                                        //获取数据
                                        UserRegisterBean value = values.iterator().next();

                                        //补充信息
                                        value.setTs(System.currentTimeMillis());
                                        value.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                                        value.setStt(DateFormatUtil.toYmdHms(window.getStart()));

                                        //输出数据
                                        out.collect(value);
                                    }
                                });
        resultDS.print("result>>>>>");

        //TODO 5.写出数据到ClickHouse
        resultDS.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_user_user_register_window values(?,?,?,?)"));

        //TODO 6.启动任务
        env.execute();
    }
}
